import SHA256 from 'crypto-js/sha256'
import fetch from '@system.fetch'
import prompt from '@system.prompt';


function uncompile(code) {
  code = decodeURI(code);
  var c = String.fromCharCode(code.charCodeAt(0) - code.length);
  for (var i = 1; i < code.length; i++) {
    c += String.fromCharCode(code.charCodeAt(i) - c.charCodeAt(i - 1));
  }
  return c;
}


function request(url, method, params, header, successCallback, failCallback) {
  header = header || {};
  //header.authorization = 'Basic aHRtbC1jbGllbnQtMDAxLSNAITpodG1sLWNsaWVudC0wMDEtI0Ah';
  header.authorization = 'Basic d3gtYXV0aC0xMjM6d3gtYXV0aC00NTY=';

  //可以做加密处理
  let paramsData = params;

  // params.httpparams101 = Math.random().toString(36).substr(2);
  // let key = '%C2%81%C3%9C%C3%A1%C3%99%C2%99%C2%A5%C3%B1%C3%B3%C2%9BK%5Eggg%C2%99%C3%8A%C3%8A%C3%8A%C3%97%C2%94KMZoq';
  // params.httpparams102 = SHA256(params.httpparams101 + uncompile(key)).toString();

  fetch.fetch({
    url: url,
    data: params || {},
    method: method || 'GET',
    //设置header
    // header: { 'content-type': 'application/x-www-form-urlencoded' },post
    // 'content-type': 'application/json' // 默认值
    header: header,
    success: (res) => {
      var data = JSON.parse(res.data);

      if (data.code == 0) {
        successCallback(data);
      } else if (data.code == 1) {

      }
      else if (data.code == 2) {

      }


    },
    fail: (err) => {
      // console.log(err);
      failCallback(err)
    },
    //不管是成功还是失败都要执行的函数
    complete: () => {

    }

  });
}

let ajax = {
  get: (url, params, header, successCallback, failCallback) => {
    request(url, 'GET', params, {'content-type': 'application/json'}, successCallback, failCallback)
  },
  post: (url, params, header, successCallback, failCallback) => {
    request(url, 'POST', params, {'content-type': 'application/x-www-form-urlencoded'}, successCallback, failCallback)
  }
};

export default ajax
